package com.hl.order.controller;

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.hl.order.dto.LoginRequest;
import com.hl.order.dto.RegisterRequest;
import com.hl.order.dto.LoginResponse;
import com.hl.order.domain.User;
import com.hl.order.service.IUserService;

/**
 * 用户认证控制器
 *
 * @author ruoyi
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/api/auth")
public class UserAuthController
{
    @Autowired
    private IUserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public AjaxResult login(@Valid @RequestBody LoginRequest loginRequest)
    {
        try {
            LoginResponse loginResponse = userService.login(loginRequest);
            return AjaxResult.success("登录成功", loginResponse);
        } catch (RuntimeException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public AjaxResult register(@Valid @RequestBody RegisterRequest registerRequest)
    {
        try {
            String result = userService.register(registerRequest);
            return AjaxResult.success(result);
        } catch (RuntimeException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 验证token并获取用户信息
     */
    @GetMapping("/userInfo")
    public AjaxResult getUserInfo(@RequestHeader("Authorization") String token)
    {
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            User user = userService.validateToken(token);
            if (user == null) {
                return AjaxResult.error("token无效或已过期");
            }
            
            // 不返回密码等敏感信息
            user.setUserPassword(null);
            user.setPaymentPassword(null);
            
            return AjaxResult.success("获取用户信息成功", user);
        } catch (Exception e) {
            return AjaxResult.error("获取用户信息失败");
        }
    }

    /**
     * 检查手机号是否已注册
     */
    @GetMapping("/checkPhone")
    public AjaxResult checkPhone(String userTel)
    {
        try {
            User user = userService.selectUserByUserTel(userTel);
            if (user != null) {
                return AjaxResult.error("该手机号已注册");
            }
            return AjaxResult.success("手机号可用");
        } catch (Exception e) {
            return AjaxResult.error("检查失败");
        }
    }
}
